<template>
  <el-container class="container">
    <!-- 左侧树 -->
    <el-aside width="300px" class="aside">
      <div class="btn-group">
        <el-button type="primary" size="mini" plain @click="addBrotherNode">添加同级文件夹</el-button>
        <el-button type="primary" size="mini" plain @click="addChildNode">添加子文件夹</el-button>
      </div>
      <el-tree
        :data="treeData"
        node-key="id"
        :props="{ label: 'name' }"
        highlight-current
        default-expand-all
        :expand-on-click-node="false"
        :render-content="renderContent"
        @current-change="onTreeNodeChecked">
      </el-tree>
    </el-aside>
    <!-- 右侧顶部筛选 -->
    <div class="app-container">
      <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="一级题型" prop="firstLevelType">
          <el-select v-model="queryParams.firstLevelType" placeholder="请选择一级题型" clearable size="small">
            <el-option
              v-for="dict in firstLevelQuestion"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="难度" prop="difficulty">
          <el-select v-model="queryParams.difficulty" placeholder="请选择难度" clearable size="small">
            <el-option
              v-for="dict in dict.type.question_difficulty"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="题目" prop="descrip">
          <el-input
            v-model="queryParams.descrip"
            placeholder="请输入题目"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="知识点" prop="pointIds">
          <el-select v-model="queryParams.pointIds" placeholder="请选择知识点" multiple clearable size="small">
            <el-option
              v-for="item in pointData"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="triggerOpen"
          >添加题目</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleExport"
          >导出选中</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
          >删除选中</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExportAll"
          >导出全部</el-button>
        </el-col>
      </el-row>
      <!-- 右侧表格 -->
      <el-table v-loading="loading" :data="questionList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="题目" align="center" prop="descrip" />
        <el-table-column label="一级题型" align="center" prop="firstLevelTypeName" />
        <el-table-column label="二级题型" align="center" prop="secondLevelTypeName" />
        <el-table-column label="难度" align="center" prop="difficulty">
          <template slot-scope="scope">
            <span>{{parseDifficulty(scope.row.difficulty)}}</span>
          </template>
        </el-table-column>
        <el-table-column label="使用次数" align="center" prop="useNum" />
        <el-table-column label="创建者" align="center" prop="createByName" />
        <el-table-column label="创建日期" align="center" prop="createTime" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
            >修改</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="pageData.pageNum"
        :limit.sync="pageData.pageSize"
        @pagination="getList"
      />
      <!-- 添加文件夹对话框 -->
      <el-dialog title="添加文件夹" @close="onDirClose" :visible.sync="addDirVisible">
        <el-input v-model="dirName" placeholder="请填写文件夹名称"></el-input>
        <span slot="footer" class="dialog-footer">
          <el-button @click="onDirClose">取 消</el-button>
          <el-button type="primary" @click="onDirConfirm">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 添加或修改题目对话框 -->
      <question-drawer :open.sync="open" :initData="record" :libId="curNode.id" @onOk="handleOk" />
    </div>
  </el-container>
</template>

<script>
import {
  getQuestionTypeList,
  getDirTree,
  addDirTreeNode,
  listQuestion,
  getQuestion,
  delQuestion
} from "@/api/publicManage/questionBase";
import { getTree } from "@/api/resourceEditor/publicResourceManagement";
import QuestionDrawer from './components/questionDrawer.vue';

export default {
  name: "Question",
  dicts: ['question_difficulty'],
  components: { QuestionDrawer },
  data() {
    return {
      // 左侧树
      treeData: [],
      curNode: {},
      addDirVisible: false,
      dirName: '',
      // 弹窗显隐
      open: false,
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 题目表格数据
      questionList: [],
      // 查询参数
      queryParams: {
        isPublic: 1,
        courseId: -1,
        teacherId: -1,
        firstLevelType: null,
        difficulty: null,
      },
      // 分页参数
      pageData: {
        pageNum: 1,
        pageSize: 10,
      },
      firstLevelQuestion: [],
      pointData: [],
      record: {}
    };
  },
  created() {
    this.fetchTreeData();
    this.fetchFirstLevel();
    this.fetchKnowledge();
    this.getList();
  },
  methods: {
    // 获取一级题型
    fetchFirstLevel() {
      const params = { typeLevel: 1 };
      getQuestionTypeList(params).then(({ code, data }) => {
        if (code === 200) {
          this.firstLevelQuestion = data.map(item => ({ label: item.name, value: item.id }));
        }
      });
    },
    // 获取知识点列表
    fetchKnowledge() {
      getTree('').then(({ code, data }) => {
        if (code === 200) {
          this.pointData = data.rows.map(item => ({ label: item.name, value: item.id }));
        }
      });
    },
    // 获取左侧菜单树
    fetchTreeData() {
      const { isPublic, courseId, teacherId } = this.queryParams;
      getDirTree({ isPublic, courseId, teacherId }).then(({ code, data }) => {
        if (code === 200) {
          this.treeData = data instanceof Array ? data : [data];
        }
      });
    },
    // 解析表格难度字段
    parseDifficulty(id) {
      const result = this.dict.type.question_difficulty.find(item => item.value == id);
      return result ? result.label : '';
    },
    onTreeNodeChecked(node) {
      this.curNode = node;
      this.getList();
    },
    onDirClose() {
      this.addDirVisible = false;
      this.dirName = '';
    },
    onDirConfirm() {
      this.addDirVisible = false;
      const { curNode: { targetId }, queryParams: { isPublic, courseId, teacherId } } = this;
      const reqBody = { name: this.dirName, parentId: targetId, isPublic, courseId, teacherId };
      const loading = this.$loading({ lock: true });
      addDirTreeNode(reqBody).then(() => {
        loading.close();
        this.fetchTreeData();
      }).catch(() => {
        loading.close();
      });
    },
    addBrotherNode() {
      const { id, parentId } = this.curNode;
      if (!id) {
        this.$message({
          message: '请选择文件夹',
          type: 'warning'
        });
      } else {
        this.curNode = { ...this.curNode, targetId: parentId };
        this.addDirVisible = true;
      }
    },
    addChildNode() {
      const { id } = this.curNode;
      let targetId = -1;
      if (id) targetId = id;
      this.curNode = { ...this.curNode, targetId };
      this.addDirVisible = true;
    },
    triggerOpen() {
      if (!this.curNode.id) {
        this.$message({
          message: '请先选择文件夹',
          type: 'warning'
        });
      } else {
        this.record = {};
        this.open = true;
      }
    },
    async handleOk({ formData, submitFunc }) {
      const { isPublic, courseId, teacherId } = this.queryParams;
      await submitFunc({ ...formData, isPublic, courseId, teacherId });
      this.open = false;
      this.getList();
    },
    dirEdit(data) {
      console.log(data);
    },
    dirDel(data) {
      console.log(data);
    },
    // 自定义左侧树条目
    renderContent(_, { node, data }) {
      return (
        <span class="custom-tree-node">
          <div class="tree-node-label" title={node.label}>{node.label}</div>
          <div class="tree-node-right">
            <i class="el-icon-edit icon-show" on-click={() => this.dirEdit(data)}></i>
            <i class="el-icon-delete icon-show" on-click={() => this.dirDel(data)}></i>
          </div>
        </span>
      );
    },
    filterObjShallow(obj) {
      const result = {};
      Object.keys(obj).map(item => {
        if (!['', null, NaN].includes(obj[item]) && obj[item]?.length != 0) {
          result[item] = obj[item];
        }
      });
      return result;
    },
    /** 查询题目列表 */
    getList() {
      this.loading = true;
      const params = JSON.parse(JSON.stringify(this.queryParams));
      params.libPath = this.curNode.path || null;
      const diff = params.difficulty ? Number(params.difficulty) : null;
      listQuestion(this.filterObjShallow({ ...params, difficulty: diff }), this.pageData).then(response => {
        this.questionList = response.data.rows;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.pageData.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      const id = row.id;
      getQuestion(id).then(response => {
        this.record = response.data;
        this.open = true;
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除题目编号为"' + ids + '"的数据项？').then(function() {
        return delQuestion(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('question/question/export', {
        ...this.queryParams
      }, `question.xlsx`)
    },
    /** 导出所有按钮操作 */
    handleExportAll() {
      this.download('question/question/exportAll', {}, `question.xlsx`)
    }
  }
};
</script>

<style lang="scss" scoped>
@import './index.scss';
</style>